﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using ZXing;
using ZXing.Common;
using ZXing.QrCode.Internal;
namespace ProducTXM
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void btn_Make_Click(object sender, EventArgs e)
        {
            int startnum = 0;
            int endnum = 0;
            int picwid = 200;
            int pichei = 100;
            if (txtbox_Picwdith.Text.Trim().TrimStart("0".ToArray()).Length == 0)
            { txtbox_Picwdith.Text = picwid.ToString(); }
            if (txtbox_Picheight.Text.Trim().TrimStart("0".ToArray()).Length == 0)
            { txtbox_Picheight.Text = pichei.ToString(); }
            if ((txtbox_Startnum.Text.Trim().TrimStart("0".ToArray()).Length==0) ||(txtbox_Endnum.Text.Trim().TrimStart("0".ToArray()).Length==0))
            {
                MessageBox.Show("开始编号或者结束编号不能为空！");
                return;               
            }

            else if  (!isNumberic(txtbox_Picheight.Text.Trim().TrimStart("0".ToArray()), out pichei)||!isNumberic(txtbox_Picwdith.Text.Trim().TrimStart("0".ToArray()), out picwid) || !isNumberic(txtbox_Startnum.Text.Trim().TrimStart("0".ToArray()),out startnum) || (!isNumberic(txtbox_Endnum.Text.Trim().TrimStart("0".ToArray()), out endnum)))
            {
                MessageBox.Show("开始编号或者结束编号必须为不为0开头的数字！");
                return;
            }
            else if (startnum>=endnum)
            {
                MessageBox.Show("开始编号必须小于结束编号！");
                return;
            }
            btn_Make.Enabled = false;
            try
            {
                
                string curdir = Environment.CurrentDirectory;
                var dt = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString();
                string usedir = curdir + @"\" + dt;
                //MessageBox.Show(usedir);return;
                    
                if (!Directory.Exists(usedir))
                {
                    Directory.CreateDirectory(usedir);
                }
                for (int i = startnum; i <= endnum; i++)
                {
                    MakeTXM(i.ToString(), curdir + @"\logo.png", picwid, pichei, usedir + @"\" + i.ToString() + @".jpg");
                }
            }
            catch (Exception ee)
            {

                MessageBox.Show(ee.ToString());
            }
            finally
            {
                btn_Make.Enabled = true;
            }
          
              
            
            
        }

        /// <summary>
        /// 生成带Logo的二维码
        /// </summary>
        /// <param name="text"></param>
        private static void MakeTXM(string text,string logopath,int picwid,int pichei,string savename)
        {
            //Logo 图片
            Bitmap logo = new Bitmap(logopath);
            //构造二维码写码器
            MultiFormatWriter writer = new MultiFormatWriter();
            Dictionary<EncodeHintType, object> hint = new Dictionary<EncodeHintType, object>();
            hint.Add(EncodeHintType.CHARACTER_SET, "UTF-8");
            hint.Add(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);

            //生成二维码 
            BitMatrix bm = writer.encode(text, BarcodeFormat.QR_CODE, picwid, pichei, hint);
            BarcodeWriter barcodeWriter = new BarcodeWriter();
            Bitmap map = barcodeWriter.Write(bm);


            //获取二维码实际尺寸（去掉二维码两边空白后的实际尺寸）
            int[] rectangle = bm.getEnclosingRectangle();

            //计算插入图片的大小和位置
            int middleW = Math.Min((int)(rectangle[2] / 3.5), logo.Width);
            int middleH = Math.Min((int)(rectangle[3] / 3.5), logo.Height);
            int middleL = (map.Width - middleW) / 2;
            int middleT = (map.Height - middleH) / 2;

            //将img转换成bmp格式，否则后面无法创建Graphics对象
            Bitmap bmpimg = new Bitmap(map.Width, map.Height, PixelFormat.Format32bppArgb);
            using (Graphics g = Graphics.FromImage(bmpimg))
            {
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                g.DrawImage(map, 0, 0);
            }
            //将二维码插入图片
            Graphics myGraphic = Graphics.FromImage(bmpimg);
            //白底
            myGraphic.FillRectangle(Brushes.White, middleL, middleT, middleW, middleH);
            myGraphic.DrawImage(logo, middleL, middleT, middleW, middleH);

            //保存成图片
            bmpimg.Save(savename, ImageFormat.Jpeg);
        }

        protected bool isNumberic(string message, out int result)
        {
            System.Text.RegularExpressions.Regex rex =
            new System.Text.RegularExpressions.Regex(@"^\d+$");
            result = -1;
            if (rex.IsMatch(message))
            {
                result = Convert.ToInt32(message);
                return true;
            }
            else
                return false;
        }

        private void txtbox_Startnum_KeyPress(object sender, KeyPressEventArgs e)
        {

            IsInputNum(sender, e);

        }
        public void IsInputNum(object sender, KeyPressEventArgs e)
        {
            //如果输入的不是数字键，也不是回车键、Backspace键，则取消该输入
            if (!(char.IsNumber(e.KeyChar)) && e.KeyChar != (char)13 && e.KeyChar != (char)8)
            {
                e.Handled = true;
            }

        }

        private void txtbox_Endnum_KeyPress(object sender, KeyPressEventArgs e)
        {
            IsInputNum(sender, e);
        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            IsInputNum(sender, e);
        }

        private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
        {
            IsInputNum(sender, e);
        }
    }
}
